/**
 * @description Provide tooling function
 */

const path = require('path')
const envConfig = require('./env')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const packageConfig = require('../package.json')
const theme = require('../src/theme/themeProvider')

exports.assetsPath = function(_path) {
  const assetsSubDirectory =
    process.env.NODE_ENV === 'production'
      ? envConfig.build.assetsSubDirectory
      : envConfig.dev.assetsSubDirectory

  return path.posix.join(assetsSubDirectory, _path)
}

exports.styleLoaders = function(options) {
  const output = [
    {
      test: /\.css$/,
      use: ExtractTextPlugin.extract({
        fallback: 'style',
        use: [
          { loader: 'css', options: { sourceMap: options.sourceMap } },
          options.usePostCSS ? 'postcss' : ''
        ]
      })
    },
    {
      test: /\.less$/,
      use: ExtractTextPlugin.extract({
        fallback: 'style',
        use: [
          { loader: 'css', options: { sourceMap: options.sourceMap } },
          {
            loader: 'less',
            options: {
              sourceMap: options.sourceMap,
              javascriptEnabled: true,
              modifyVars: theme
            }
          }
        ]
      })
    },
    {
      test: /\.scss$/,
      use: ExtractTextPlugin.extract({
        fallback: 'style',
        use: [
          { loader: 'css', options: { sourceMap: options.sourceMap } },
          {
            loader: 'sass',
            options: { sourceMap: options.sourceMap, javascriptEnabled: true }
          }
        ]
      })
    }
  ]
  return output
}

exports.createNotifierCallback = () => {
  const notifier = require('node-notifier')

  return (severity, errors) => {
    if (severity !== 'error') {
      return
    }

    const error = errors[0]
    const filename = error.file && error.file.split('!').pop()

    notifier.notify({
      title: packageConfig.name,
      message: `${severity} : ${error.name}`,
      subtitle: filename || '',
      icon: path.join(__dirname, '../favicon.ico')
    })
  }
}
